
package com.android.weather1;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class Weatherdbm {
	
  private SQLiteDatabase db;
  private DatabaseHelper dbHelper;
  
  private static final String classTagSTR = "Weatherdbm";
  private static final String dbCreateSTR =
	        "create table cities (_id integer primary key autoincrement, "
	        + "name text not null, region text not null, country text not null);";
  
  private static final String dbNameSTR = "weather";
  private static final String dbCityTableSTR = "cities";
  private static final int dbVersion = 2;
  
  private final Context dbCtx;
  
  private static class DatabaseHelper extends SQLiteOpenHelper {

      DatabaseHelper(Context context) {
          super(context, dbNameSTR, null, dbVersion);
      }

      @Override
      public void onCreate(SQLiteDatabase db) {

          db.execSQL(dbCreateSTR);
      }
      
      @Override
      public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
          Log.w(classTagSTR, "Upgrading database from version " + oldVersion + " to "
                  + newVersion + ", which will destroy all old data");
          db.execSQL("DROP TABLE IF EXISTS cities");
          onCreate(db);
      }
  }
  
  public Weatherdbm(Context ctx) {
     this.dbCtx = ctx;
  }

  public Weatherdbm open() throws SQLException {
      dbHelper = new DatabaseHelper(dbCtx);
      db = dbHelper.getWritableDatabase();
      return this;
  }

  public void close() {
      dbHelper.close();
  }
  
  public long createCity(String name, String region, String country) {
      ContentValues initialValues = new ContentValues();
      initialValues.put("name", name);
      initialValues.put("region", region);
      initialValues.put("country", country);

      return db.insert(dbCityTableSTR, null, initialValues);
  }
   
  public boolean deleteCity(long rowId) {

      return db.delete(dbCityTableSTR, "_id" + "=" + rowId, null) > 0;
  }
  
  public Cursor fetchAllCities() {

      return db.query(dbCityTableSTR, new String[] {"_id", "name",
              "region", "country"}, null, null, null, null, null);
  }
}